
import ajaxConfig from './config.js'
import axios from 'axios'

// http response 拦截器
axios.interceptors.response.use(
    response => {
        let data = response.data
        if (data.Code === "0") {
            return data.Data
        } else {
            console.log(response.config.url + "_请求异常：" + data.Code + "_" + data.Msg);
            throw data

        }
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 返回 401 清除token信息并跳转到登录页面
                    store.commit(types.LOGOUT);
                    router.replace({
                        path: 'login',
                        query: { redirect: router.currentRoute.fullPath }
                    })
            }
        }
        return Promise.reject(error.response.data)   // 返回接口返回的错误信息
    });


// http request 拦截器
// axios.interceptors.request.use(
//     config => {
//         alert('请求拦截')
//         //判断userkey是否存在，如果不存在则跳到登录页
//         // if (store.state.token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
//         //     config.headers.Authorization = `token ${store.state.token}`;
//         // }
//         return config;
//     },
//     err => {
//         return Promise.reject(err);
//     });

axios.defaults.baseURL = '/api';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers['Content-Type'] = ' application/json;charset=utf-8';

let myAjax = new Object();
let myVersions = '1_13'

myAjax.get = function (url, data) {

    let userkey = localStorage.getItem("UserKey");
    if (userkey) axios.defaults.headers['UserKey'] = userkey;
    data = data || {}
    url = url + "?v=" + myVersions

    return axios.get(url, JSON.stringify(data)).then(function (response) {
        return response;
    }).catch(function (response) {
        throw response
    })
}

myAjax.post = function (url, data) {

    let userkey = localStorage.getItem("UserKey");
    if (userkey) axios.defaults.headers['UserKey'] = userkey;
    data = data || {}
    url = url + "?v=" + myVersions
    return axios.post(url, JSON.stringify(data))
        .then(function (response) {
            return response;
        })
        .catch(function (response) {
            throw response
        })
}

myAjax.all = function (httpFunctions, callback) {
    return axios.all(httpFunctions).then(axios.spread(callback));
}

// myAjax.put={}
// myAjax.delete={}
// myAjax.patch={}

export default myAjax;
